jeDate({
    dateCell: "#dateinfo",
    format: "YYYY-MM-DD hh:mm:ss",
    isinitVal: false,
    isTime: true, //isClear:false,
})
jeDate({
    dateCell: "#dateinfo1",
    format: "YYYY-MM-DD hh:mm:ss",
    isinitVal: false,
    isTime: true, //isClear:false,
})
$(function () {
    var ws = null,
        socket = null,
        boo = false,
        count = 0,
        cmb_serId = [],
        cmb_serId = [],
        ws_serId = [],
        certificate = certificateData;
    var resultData,
        sessionId,
        logsessionId,
        Guid,
        Guid1,
        certificate,
        aircraftId, //飞机编号
        resData, //注册数据
        subDat; //订阅信息
    var gs_timer = null,
        gs_time = null;
    gs_time = new Date();
    gs_timer = setInterval(function () {
        var newTime = new Date();
        if (newTime - gs_time >= 600000) postReq({ "noResp": '@online_cnt@', "result": '未接受到数据超过10分钟(数据间隔为5分钟左右)' })
        else if (newTime - gs_time >= 420000 && newTime - gs_time < 600000) postReq({ "noResp": '@online_cnt@', "result": '未接受到数据超过6分钟(数据间隔为5分钟左右)' })
    }, 420000)

    $(".link-btn").on("click", function () {
        // var ip = $(".ip-input").val() ? $(".ip-input").val() : "ws://121.40.30.88:8080";
        var ip = $(".ip-input").val();
        if (ip) {
            linkInfoData(ip);
        }
    });

    function linkInfoData(ip, scoketSend) { //连接字段
        $('.resp-mesBox').html('');
        Guid = guid();
        Guid1 = guid();
        if (scoketSend) {
            logwebsocket(ip);
        } else {
            websocket(ip);
        }
    }
    $ws({
        variety: 'sub',
        ip: '121.40.30.88',
        certificate: certificateData,
        subscribe: "@online_cnt@",
    })

    $ws.on('message', function () {
        gs_time = new Date();
    })

    linkInfoData("ws://121.40.30.88:8080", true);
    linkInfoData("ws://121.40.30.88:8080");

    function resInfoData(Guid, scoketSend) { //注册字段
        resData = {
            'method': 'REGISTER',
            'type': 'register_req',
            'call_id': Guid,
            'info': {
                'certificate': JSON.stringify(certificate)
            }
        };
        if (scoketSend) {
            socket.send(JSON.stringify(resData));
        } else {
            ws.send(JSON.stringify(resData));
        }
    }

    function subInfoData(sessionId, Guid) { //订阅字段
        subData = {
            "method": "REGISTER",
            "type": "subscribe_req",
            "from": sessionId,
            "call_id": Guid,
            "info": {
                "subscribe": subsInfo
            }
        }
        if (subsInfo.match(/^\@[A-z]/)) {
            ws.send(JSON.stringify(subData));
        }
    }

    function sendRes(type, serverId, sendData, scoketSend) { //发送查询请求
        var searData = sendData ? sendData : {};
        var scoketSend = scoketSend ? scoketSend : false;
        var SessionId = scoketSend ? logsessionId : sessionId
        var data = {
            "method": "INFO",
            "type": type,
            "from": SessionId,
            "to": serverId,
            "call_id": Guid,
            "info": {
                "data": searData
            }
        }
        if (scoketSend) {
            socket.send(JSON.stringify(data))
        } else {
            ws.send(JSON.stringify(data));
        }
    }

    function searchSerId(type, Guid, sendData) { //发送查询请求
        var searData = sendData ? sendData : {};
        var data = {
            "method": "NOTIFY",
            "type": type,
            "from": logsessionId,
            "call_id": Guid,
            "info": {
                "data": searData
            }
        }
        socket.send(JSON.stringify(data));
    }

    function websocket(ip) { //websocket初始化
        var respCount = 1, //返回信息累计
            boo1 = boo2 = boo3 = boo4 = boo5 = boo30 = boo50 = false;
        var getRespType = [];
        var num = 0;
        var booNum = 0;
        var beign_index = 0;
        if (window.WebSocket) {
            // ws = new WebSocket('ws://121.40.30.88:8080');
            ws = new WebSocket(ip);
            ws.onopen = function (event) {
                if (ws.readyState === WebSocket.OPEN) {
                    writeToScreen("连接打开");
                    resInfoData(Guid, false);
                }
            };
            ws.onmessage = function (event) {
                resultData = JSON.parse(event.data);
                if (resultData.type == "register_resp") {
                    sessionId = resultData.info.session_id;
                    subInfoData(sessionId, Guid);//订阅
                    //高速卡口
                    sendRes("gskk_weight_stats_req", "{11EFDBDB-DE99-48D8-A23F-17AB135736AE}", req());
                    sendRes("gskk_enex_stats_req", "{11EFDBDB-DE99-48D8-A23F-17AB135736AE}", req());
                    sendRes("gskk_enex_stats_area_req", "{11EFDBDB-DE99-48D8-A23F-17AB135736AE}",
                        reqArea());
                    sendRes("gskk_weight_stats_area_req", "{11EFDBDB-DE99-48D8-A23F-17AB135736AE}",
                        reqArea());
                    sendRes("gskk_weight_stats_station_req", "{11EFDBDB-DE99-48D8-A23F-17AB135736AE}",
                        weightStation());
                    sendRes("gskk_enex_stats_station_req", "{11EFDBDB-DE99-48D8-A23F-17AB135736AE}",
                        weightStation());
                    //航空
                    sendRes("hlzh_hbdt_req", "{191A5A0E-7EF7-4044-8214-E190975A951B}", hlzhData);
                    sendRes("adsb_aircraft_list_req", "{0803C95E-B1BF-4264-BDD5-348BEC6DB7A7}");
                    // sendRes("fcz_wlhbskb_req", "{D8F91BCC-2442-4EEF-B598-B5ECDFCD3237}", hlwlhbskb);
                    sendRes("fcz_jcll_req", "{D8F91BCC-2442-4EEF-B598-B5ECDFCD3237}", hljcll);
                    //铁路
                    sendRes("tl_cz_province_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlProvince);
                    sendRes("tl_cz_name_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlName);
                    sendRes("tl_cz_time_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlTime());
                    sendRes("tl_lc_time_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlLcTime);
                    sendRes("tl_lc_sj_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlLcsj());
                    sendRes("tl_lc_df_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlLcsj());
                    sendRes("tl_get_zm_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlGet);
                    sendRes("tl_lclx_xx_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlGet);
                    sendRes("tl_cz_sxk_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlsxk());
                    sendRes("tl_cz_sxk_ys_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlsxkys());
                    //保持心跳
                    heartCheck.start();
                } else if (resultData.type == "adsb_aircraft_list_resp" && !!resultData.info.data.count) {
                    aircraftId = resultData.info.data.adsb_list[0][1];
                    var hlaircraft = {
                        "aircraft_id": aircraftId
                    }
                    sendRes("adsb_aircraft_req", "{0803C95E-B1BF-4264-BDD5-348BEC6DB7A7}", hlaircraft);
                } else if (resultData.type != "heart_beat" && !!
                    resultData.type) {
                    if (resultData.type == "@clw_dynamic_cbais@") {
                        var mesResp = resultData.info.message;
                        boo1 = true;
                        if (!mesResp || JSON.stringify(mesResp) == "{}") {
                            postReq(resultData);
                        } else {
                            if (typeof mesResp.cbmc == 'string' &&
                                typeof mesResp.jd == 'number' && typeof mesResp.wd == 'number' &&
                                typeof mesResp.sd == 'number' && typeof mesResp.hx == 'number' &&
                                typeof mesResp.xxlx == 'number') {

                            } else {
                                postReq(resultData);
                            }
                        }
                    } else if (resultData.type == "@Traffic_survey@") {
                        boo5 = true;
                        if (resultData.info.data == undefined || JSON.stringify(resultData.info.data) == {}) {
                            postReq(resultData);
                        }

                    } else if (resultData.type == "@gskk_ex@wz.zj" || resultData.type ==
                        "@gskk_en@wz.zj") {
                        if (resultData.type == "@gskk_ex@wz.zj") {
                            boo2 = true;
                        } else {
                            boo3 = true;
                        }
                        if (resultData.info.data == undefined || resultData.info.data.count ==
                            undefined || resultData.info.data
                                .list == undefined || !resultData.info.data.list instanceof Array) {
                            postReq(resultData);
                        } else {
                            console.log(resultData) //删除
                        }
                    } else if (resultData.type == "@lkxx_yys@") {
                        boo4 = true;
                        if (!resultData.info.datafrom == undefined || !resultData.info.reporttime ==
                            undefined || !resultData.info
                                .traffic == undefined) {
                            postReq(resultData);
                        } else {
                            console.log(resultData) //删除
                        }
                    }else if (resultData.type == "330000@gps@809") {
                        boo30 = true;
                    } else if (resultData.type == "50303@gps@809") {
                        boo50 = true
                    } else {
                        if (respType.indexOf(resultData.type) > -1) { //不包含返回-1
                            getRespType.push(resultData.type);
                            checkResData(resultData.type);
                            respCount++;
                        }
                    }
                    boo = boo1 && boo2 && boo3 && boo4 && boo5 && boo30 && boo50 && respCount == 21; //所有订阅信息和查询信息都响应式boo为true，断开连接，1小时后重连
                    if (booNum == 0) {
                        booNum = booNum + 1
                        if (booNum == 1) {
                            setTimeout(function () {
                                if (!boo) {
                                    var boo1NoResp = !boo1 ? postReq({ "noResp": "@clw_dynamic_cbais@", "result": "无响应" }) : ""
                                    //var boo2NoResp = !boo2 ? postReq({"noResp":"@gskk_ex@wz.zj","result":"无响应"}) : ""
                                    //var boo3NoResp = !boo3 ? postReq({"noResp":"@gskk_en@wz.zj","result":"无响应"}) : ""
                                    //var boo4NoResp = !boo4 ? postReq({"noResp":"@lkxx_yys@","result":"无响应"}) : ""
                                    var boo5NoResp = !boo5 ? postReq({ "noResp": "@Traffic_survey@", "result": "无响应" }) : ""
                                    var boo30NoResp = !boo30 ? postReq({"noResp":"330000@gps@809","result":"无响应"}) : ""
                                    var boo50NoResp = !boo50 ? postReq({"noResp":"50303@gps@809","result":"无响应"}) : ""
                                    for (var i = 0; i < getRespType.length; i++) {
                                        if (respType.indexOf(getRespType) == -1) {
                                            // postReq({"noResp":respType,"result":"无响应"})
                                            console.log(getRespType);
                                        }
                                    }
                                    reLink();
                                }
                            }, 20 * 60 * 1000)
                        }
                    }
                    if (boo) {
                        num = num + 1;
                        if (num == 1) {
                            reLink();
                        }
                    }
                }
            };
            ws.onclose = function (event) {
                heartCheck.clear();
                writeToScreen("连接关闭");
            };
            ws.onerror = function (event) {
                writeToScreen("连接出错");
            };
        } else {
            alert("您的浏览器不支持websocket~");
        }
    }

    function logwebsocket(ip) { //websocket初始化
        var beign_index = 0;
        if (window.WebSocket) {
            socket = new WebSocket(ip);
            socket.onopen = function (event) {
                if (socket.readyState === WebSocket.OPEN) {
                    writeToScreen("日志查询连接打开");
                    resInfoData(Guid, true);
                }
            };
            socket.onmessage = function (event) {
                resultData = JSON.parse(event.data);
                if (resultData.type == "register_resp") {
                    logsessionId = resultData.info.session_id;
                    //查询服务ID
                    searchSerId("@ws_find@", Guid);
                    searchSerId("@cmb_find@", Guid1);
                    //日志查询
                    $(".serchBtn").on("click", function () {
                        var logData = {
                            "begin_time": $(".startTime").val(),
                            "end_time": $(".endTime").val(),
                            "begin_index": beign_index,
                            "count": parseInt($(".recordNum").val()),
                        }
                        if (!$(".selectSer").val()) {
                            alert("请先选择协议类型再点击查询按钮");
                        } else if ($(".selectSer").val() == "--请选择--") {
                            alert("请选择协议类型");
                        } else {
                            var logReq = $(".selectSer").val().split("_")[0].slice(1) + "_log_req";
                            var sendSerId = $(".selectSer").val().split("_")[0].slice(1) == "ws" ? ws_serId : cmb_serId
                            if (sendSerId.length > 0) {
                                for (var i in sendSerId) {
                                    sendRes(logReq, sendSerId[i], logData, true);
                                }
                            } else {
                                setTimeout(function () {
                                    alert("未获取到服务ID，请刷新重连")
                                }, 1500);
                            }
                        }
                        beign_index += parseInt($(".recordNum").val());
                    })
                    //保持心跳
                    heartCheck.start(true);
                } else if (resultData.type == "cmb_find_resp") {
                    //状态查询
                    sendRes("cmb_status_req", resultData.info.data.general.guid, {}, true);
                    cmb_serId.push(resultData.info.data.general.guid);
                } else if (resultData.type == "ws_find_resp") {
                    //状态查询
                    sendRes("ws_status_req", resultData.info.data.general.guid, {}, true);
                    ws_serId.push(resultData.info.data.general.guid);
                } else if (resultData.type == "cmb_log_resp") {
                    if (resultData.info.data["log_list"]) {
                        logRender(resultData.info.data.log_list);
                    }
                } else if (resultData.type == "ws_log_resp") {
                    if (resultData.info.data["log_list"]) {
                        logRender(resultData.info.data.log_list);
                    }
                } else if (resultData.type == "ws_status_resp") {
                    var data = resultData.info.data
                    if (data[2] > 80 || data[5] > 80) {
                        console.log(data);
                        var configUrl = resultData.type.split("_")[0] + '_get_config_req';
                        sendRes(configUrl, data[1], {}, true);
                    }
                } else if (resultData.type == "cmb_status_resp") {
                    var data = resultData.info.data
                    if (data[2] > 80 || data[5] > 80) {
                        console.log(data);
                        var configUrl = resultData.type.split("_")[0] + '_get_config_req';
                        sendRes(configUrl, data[1], {}, true);
                    }
                } else if (resultData.type == "ws_get_config_resp") {
                    var cpuError = {
                        "cpuser": "cmb",
                        "cpuIp": resultData.info.data.general.ip[0]
                    }
                    postReq(cpuError);
                } else if (resultData.type == "cmb_get_config_resp") {
                    var cpuError = {
                        "cpuser": "cmb",
                        "cpuIp": resultData.info.data.general.ip[0]
                    }
                    //postReq(cpuError);
                } else if (resultData.type == "adsb_aircraft_list_resp" && !!resultData.info.data.count) {
                    aircraftId = resultData.info.data.adsb_list[0][1];
                    var hlaircraft = {
                        "aircraft_id": aircraftId
                    }
                    sendRes("adsb_aircraft_req", "{0803C95E-B1BF-4264-BDD5-348BEC6DB7A7}", hlaircraft);
                } else {
                }
            };
            socket.onclose = function (event) {
                heartCheck.clear(true);
            };
            socket.onerror = function (event) {
                writeToScreen("连接出错");
            };
        } else {
            alert("您的浏览器不支持websocket~");
        }
    }

    var heartCheck = { //心跳
        timeout: 50000, //50s
        timeoutObj: null,
        timeoutScoket: null,
        clear: function (scoketSend) {
            if (scoketSend) {
                clearInterval(this.timeoutScoket);
            } else {
                clearInterval(this.timeoutObj);
            }

        },
        start: function (scoketSend) {
            var SessionId = scoketSend ? logsessionId : sessionId
            var data = {
                "method": "INFO",
                "from": SessionId,
                "type": "heart_beat",
                "call_id": Guid
            }
            if (scoketSend) {
                this.timeoutScoket = setInterval(function () {
                    if (socket.readyState === WebSocket.OPEN) {
                        socket.send(JSON.stringify(data));
                    }
                }, this.timeout);
            } else {
                this.timeoutObj = setInterval(function () {
                    if (socket.readyState === WebSocket.OPEN) {
                        ws.send(JSON.stringify(data));
                    }
                }, this.timeout);
            }
        }
    }

    function reLink() { //重连
        ws.close();
        ws = null;
        boo = false;
        setTimeout(function () {
            linkInfoData("ws://121.40.30.88:8080");
        }, 1000 * 60 * 40); //1000*60*60 一个小时连接一次
    }

    // subAjax();

    function checkResData(type) { //检查返回的字段是否有误
        if (resultData.type == type) {
            if (resultData.info.result.code === 0 && resultData.info.data != undefined) {
                for (var key in resultData.info.data) {
                    if (numberType.indexOf(key) > -1) {
                        if (typeof resultData.info.data[key] != "number") {
                            postReq(resultData);
                        }
                    } else if (key == "area") {
                        if (areaArr.indexOf(resultData.info.data[key]) == -1) {
                            postReq(resultData);
                        }
                    }
                }
            } else {
                postReq(resultData);
            }
        }
    }

    $(".get-error").on("click", function () {
        $.get("http://116.62.174.108:8800/error/get", function (result) {
            funDownload(JSON.stringify(result), 'error.json');
        });
    });

    function guid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }
});